package com.helwen.tools.zhijiang;

import org.apache.poi.xwpf.usermodel.*;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 读取word，  只是读取国标中的word固定文件。  拼成将xml格式参数转成json参数，去调东软件平台将枝江数据上传到宜昌平台中。
 * 生成建表sql 与xml形式
 * @author Christmas_G
 *
 */
public class findWordFile {
    @Test
    public void readWordCreateSql() throws FileNotFoundException, IOException {


        try {
            //String filepath="C:\\develop\\docs\\枝江\\宜昌市一体化全民健康信息平台接口文档\\医疗";
            //String filepath="D:\\123\\全民健康\\医疗\\EMR";
            //String filepath="D:\\123\\全民健康\\医疗\\HIS及其他";
            String filepath="C:\\develop\\docs\\枝江\\公共卫生";
            File file=new File(filepath);//文件夹
            String[] filelist = file.list();
            String protocol="";
            String[] arr={"ADI_DRUG_INFO","adi_drug_info"};
            for (int i = 0; i < filelist.length; i++) {
                String filename = filelist[i];
                File readfile = new File(filepath + "\\" + filename);
                if(filename.startsWith("~")){
                    continue;
                }
                XWPFDocument document = new XWPFDocument(new FileInputStream(readfile));
                // 获取word中的所有段落与表格
                List<IBodyElement> elements = document.getBodyElements();

                for (IBodyElement element : elements) {
                    // 段落
                    if (element instanceof XWPFParagraph) {
                        protocol= getTableCellText((XWPFParagraph) element);
                        for(String str:arr){
                            if(protocol.indexOf(str)>0){
                                System.out.println("文件名："+filename+"中包含标准："+str);
                            }
                        }

                    }

                }
                document.close();
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取段落内容
     *
     * @param paragraph
     */
    private void getParagraphText(XWPFParagraph paragraph) {
        // 获取段落中所有内容
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs.size() == 0) {
            System.out.println("按了回车（新段落）222222");
            return;
        }
        StringBuffer runText = new StringBuffer();
        for (XWPFRun run : runs) {
            runText.append(run.text());
        }
        if (runText.length() > 0) {
            runText.append("，对齐方式222222：").append(paragraph.getAlignment().name());
            System.out.println(runText);
        }
    }

    private String getTableCellText(XWPFParagraph paragraph) {
        // 获取段落中所有内容
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs.size() == 0) {
            return "";
        }
        StringBuffer runText = new StringBuffer();
        for (XWPFRun run : runs) {
            runText.append(run.text());
        }
        //System.out.println(runText);

        return runText.toString();
    }

    /**
     * 获取表格内容
     *
     * @param table
     */
    private void getTabelText(XWPFTable table,String protocol) throws Exception{
        List<XWPFTableRow> rows = table.getRows();
        File file=new File("C:\\develop\\docs\\template\\健康体检问询记录.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream, "UTF-8");
        int x=0;
        StringBuffer ceateSql=new StringBuffer("create table HIIP.tablename(");
        StringBuffer commonSql=new StringBuffer("");
        StringBuffer xmlStr=new StringBuffer("");
        StringBuffer jsonStr=new StringBuffer("");
        Map<String,String> checkMp=new HashMap<>();
        for (XWPFTableRow row : rows) {
            if(x==0){
                x++;
                continue;
            }
            List<XWPFTableCell> cells = row.getTableCells();
            /*int i=0;
            for (XWPFTableCell cell : cells) {
                // 简单获取内容（简单方式是不能获取字体对齐方式的）
                // System.out.println(cell.getText());
                // 一个单元格可以理解为一个word文档，单元格里也可以加段落与表格
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
                    getTableCellText(paragraph);
                }
            }*/
            List<XWPFParagraph> ycpar = cells.get(6).getParagraphs();//取第7个单元格中的值
            String ycfield=getTableCellText(ycpar.get(0));//

            //获取字段
            List<XWPFParagraph> paragraphs = cells.get(0).getParagraphs();//取第一个单元格中的值
            String path=getTableCellText(paragraphs.get(0));//
            if(path==null || path.equals("")){
                continue;
            }
            if(checkMp.containsKey(path)){
                System.out.println("有两个："+path);
            }else {
                checkMp.put(path,path);
            }
            String xmlpath=path.replace( " ",  "");
            ceateSql.append(path+" varchar2(50),\r\n");
            //获取注释
            List<XWPFParagraph> explans = cells.get(2).getParagraphs();//取第4个单元格中的值。
            String explain=getTableCellText(explans.get(0));//

            commonSql.append("comment  on  column  tablename.").append(path).append(" is '").append(explain).append("';\r\n");
            //xmlStr.append("<!-- ").append(explain).append(" -->\r\n");
            xmlStr.append("<").append(path).append("> </").append(path).append("> \r\n");
            jsonStr.append("\"").append(ycfield).append("\" : \"${info.").append(path).append(" }\",\r\n");

        }
        //osw.write(ceateSql.toString()+"\r\n");
        //osw.write(commonSql.toString());
        //osw.write("\r\n");
        osw.write(xmlStr.toString());
        osw.write("\r\n");
        osw.write("\r\n");
        osw.write(jsonStr.toString());
        osw.flush();
        osw.close();
        fileOutputStream.close();

    }

    private String getSpecificationWord(String word){
        if(word.length()>1){
            return word.substring(0, 1).toUpperCase()+word.substring(1);
        }else {
            return word;
        }
    }
}
